<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switch-fullscreen
    cancel-text="关闭"
    @cancel="handleCancel"
    :maskClosable="false"
    @ok="handleCancel"
  >
    <!--    <hte-file-class-form ref="realForm" @ok="submitCallback" :disabled="disableSubmit"></hte-file-class-form>-->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-input-search placeholder="对象名称模糊查询" style="width: 200px;margin-right:8px" @search="onSearch" />
      <a-button icon="plus" @click="handleAdd">添加共享</a-button>
      <a-button icon="delete" @click="handleDel">删除</a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        row-key="id"
        :columns="columns"
        :data-source="tableData"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      />
    </div>

    <!-- <a-modal
      title="添加共享范围"
      :width="800"
      :visible="addVisible"
      :confirm-loading="confirmLoading"
      @ok="handleAddOk"
      :maskClosable="false"
      @cancel="handleAddCancel"
    >
      <a-form-model ref="form" :model="model" :rules="validatorRules" style="width:700px;">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="对象类型：" :label-col="labelCol" :wrapper-col="wrapperCol" prop="objectType">
              <a-radio-group v-model="model.objectType" name="radioGroup" :default-value="1" @change="handleObjectChange">
                <a-radio :value="1">
                  私有组
                </a-radio>
                <a-radio :value="2">
                  发送人员
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="对象名称" :label-col="labelCol" :wrapper-col="wrapperCol" prop="objectId">
              <a-select
                ref = "selectRef"
                v-model="model.objectId"
                mode="multiple"
                placeholder="请输入对象名称"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? '找不到记录' : null"
                @search="fetchObj"
                @change="selectObjectChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="d in objData" :key="d.value" :value="d.value">
                  {{ d.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="权限" :label-col="labelCol" :wrapper-col="wrapperCol" prop="authority">
              <a-select
                v-model="model.authority"
                mode="multiple"
                placeholder="请选择权限"
              >
                <a-select-option
                  v-for="option in authorityOptions"
                  :key="'auth'+  option.value"
                  :value="option.value"
                  :defaultValue="[1]"
                >{{ option.label }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal> -->
    <file-range-add :visible="addVisible" :saveData='tableData' :fileType="classId" ref="fileRangeAdd" @handleAddCancel='handleAddCancel' @handleAddOk="handleAddOk"></file-range-add>
  </j-modal>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
import FileRangeAdd from './FileRangeAdd'
export default {
  name: 'HteFileClassRangeModal',
  components: {
    FileRangeAdd
  },
  data() {
    return {
      authorityOptions: [
        { value: '1', label: '查阅' },
        { value: '2', label: '编辑' },
        { value: '3', label: '下载' },
        { value: '4', label: '可废除' }
      ],
      classId: '',
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '对象类型 ',
          align: 'center',
          dataIndex: 'objectType',
          customRender: (text) => {
            if (text == 1) {
              return '私有组';
            } else if (text == 2) {
              return '发送人员';
            }else if (text == 3) {
              return '组织架构';
            }
            else if (text == 4) {
              return '所有人公开';
            }
            return text
          }
        },

        {
          title: '对象名称',
          align: 'center',
          dataIndex: 'objectName'
        },
         
        {
          title: '权限',
          align: 'center',
          dataIndex: 'authority',
          customRender: (text) => {
            var str = ''
            if (text && text.indexOf('1') >= 0) {
              str += '查阅,'
            }
            if (text && text.indexOf('2') >= 0) {
              str += '编辑,'
            }
            if (text && text.indexOf('3') >= 0) {
              str += '下载,'
            }
            if (text && text.indexOf('4') >= 0) {
              str += '可废除,'
            }
             if (text && text.indexOf('5') >= 0) {
              str += '一级发布,';
            }
            if (str.length > 1) {
              return str.substr(0, str.length - 1)
            }
            return str
          }
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUserName'
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '客户端',
          align: 'center',
          dataIndex: 'client'
        }
      ],
      tableData: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        name: ''
      },
      loading: false,
      title: '',
      width: 800,
      visible: false,
      disableSubmit: false,
      data: [],
      selectedRowKeys: [],
      rowKeyIndex: -1,
      addVisible: false,
      confirmLoading: false,
      model: { 'objectType': 1, 'client': '海芯' ,'objectId':[]},
      validatorRules: {
        authority: [{ required: true, message: '请选择权限' }],
        objectId: [{ required: true, message: '请输入选择' }],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      objData: [],
      fetching: false,
      url: {
        save: '/lib/hteFileClassRange/add',
        list: '/lib/hteFileClassRange/list',
        deleteBatch: '/lib/hteFileClassRange/deleteBatch',
        getUserList: '/lib/hteFileClass/getUserList',
        getGroupList: '/lib/hteLibraryGroup/groupList'
      }
    }
  },
  methods: {
    add(classId) {
      this.visible = true
      this.classId = classId
      this.ipagination.objectName = ''
      this.loadRange()
    },

    close() {
      this.$emit('close')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },

    handleAdd() {
      this.addVisible = true
      

    },
    handleAddOk(data) {
      data.classId = this.classId;
      
      postAction(this.url.save, data).then((res) => {
            if (res.success) {
              this.ipagination.objectName = ''
              this.loadRange()
              this.handleAddCancel();
            }
          })
    },
    handleAddCancel() {
      this.addVisible = false
    },
    loadRange() {
      this.tableData = []
      let param = Object.assign({}, this.ipagination)
      delete param.pageSizeOptions
      delete param.showTotal
      getAction(this.url.list + '/' + this.classId, param).then((res) => {
        if (res.success) {
          if (res.result.total) {
            this.ipagination.total = res.result.total
          } else {
            this.ipagination.total = 0
          }
          this.tableData = res.result.records
        }
      })
    },
    onSearch(objectName){
        this.ipagination.objectName = objectName
        this.loadRange();
    },
    handleSave() {
      console.log(this.data)
      const that = this
      this.data.forEach((it, index) => {
        it.classId = that.classId
      })
      postAction(this.url.save, this.data).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleDel() {
      console.log('selectedRowKeys: ', this.selectedRowKeys)
      var that = this
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中数据?',
        onOk: function() {
          let ids = ''
          that.selectedRowKeys.forEach(key => {
            if (key > 0) {
              ids += key + ','
            }
            const index = that.data.findIndex(
              v => v.id === key
            )
            that.data.splice(index, 1)
          })
          getAction(that.url.deleteBatch, { ids: ids }).then((res) => {
            if (res.success) {
              that.loadRange()
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    fetchObj(val) {
      this.objData = []
      this.fetching = true
      let url = this.url.getGroupList
      if (this.model.objectType === 2) {
        url = this.url.getUserList
      }
      getAction(url, { 'name': val }).then((res) => {
        if (res.success) {
          this.objData = res.result
          if (res.result.length > 0) {
            this.fetching = false
            if (this.model.objectType == 2) {
              res.result.forEach(it => {
                this.objData.push({ 'label': it.realname, 'value': it.username })
              })
            } else {
              res.result.forEach(it => {
                this.objData.push({ 'label': it.name, 'value': it.id })
              })
            }
          }
        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order === 'ascend' ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.ipagination.pageNo = this.ipagination.current
      this.loadRange()
    },
    handleObjectChange(){
      this.model.objectId=[]
      this.objData=[]
    },
    selectObjectChange(){
      this.$refs.selectRef.blur()
    }
  }
}
</script>
